package com.xzakota.minesweeper;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 只允许运行一个线程的线程池，并且如果提交的旧线程未结束，则无法提交新线程
 *
 * @author Xzakota
 */
public class SingleTaskExecutor {
    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private static final AtomicBoolean taskRunning = new AtomicBoolean(false);

    public static void submitTask(Runnable task) {
        if (taskRunning.compareAndSet(false, true)) {
            executorService.submit(() -> {
                try {
                    task.run();
                } finally {
                    taskRunning.set(false);
                }
            });
        } else {
            throw new RuntimeException("提交的旧线程未结束，无法提交新线程!");
        }
    }

    public static void shutdown() {
        executorService.shutdown();
    }
}
